local TcpCon = {
    _svr = nil,
    _iscon = false,
    _scheduler = nil,
}
--==================================
--default params
local wifi = wifi
local net = net

-- -- local lib_msgpack = require("lib_msgpack")
local PROTO_MAP = require("PROTO")
--==================================


function TcpCon:heartBeat(pcont, interval)
    local function ping()
        print("send ping...")
        self._svr:send(pcont)
    end
    local schedule_heatbeat =
    tmr.create():alarm(
    interval,
    tmr.ALARM_AUTO,
    ping
)
    self._scheduler = schedule_heatbeat
    return self
end

function TcpCon:_chkContent(sock, cont)
    print("receive data-->>"..cont)
    local sep_cont = cont
    --todo sep content 
    if type(self._on_rcv_func)== "function" then
        self._on_rcv_func(sep_cont)
    end
end

function TcpCon:onReceive(cb)
    self._on_rcv_func = cb
    return self
end

function TcpCon:onConnect(cb)
    self._on_connect = cb
    return self
end

function TcpCon:send(cont, ispong)
    if not self._iscon then return end 
    local msg = ispong and cont or "test_msgpack"
    print("tcp client send :%s", tostring(msg))
    self._svr:send(msg)
    return self
end

function TcpCon:connect(domain, port)
    local tcp_svr = net.createConnection(net.TCP)
    print("connecting...")
    tcp_svr:on(
        "connection",
        function(conn)
            self._iscon = true
            if type(self._on_connect) == "function" then 
                self._on_connect()
            end
        end
    )
    tcp_svr:on(
        "receive", 
        handler(self, self._chkContent)
    )
    tcp_svr:on(
        "disconnection",
        function(conn, errcode)
            print("disconnection!reason is ->".. tostring(errcode))
            print("try to re-connected!")
            tcp_svr:connect(port, domain)
        end
    )
    tcp_svr:connect(port, domain)
    self._svr = tcp_svr
    return self
end

function TcpCon:close()
    if self._scheduler then
        self._scheduler:stop()
    end
end
return TcpCon
